package org.jugile.jsontmpl.domain;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.jugile.util.Jugile;

/**
 * Context for parsing.
 * @author rahkojuk
 */
public class Ctx extends Jugile {

	private List<String> includestack = new ArrayList<String>();
	
	public boolean push(String fname) {
		//print("::fname: " + fname);
		if (rootDir == null) {
			File rd = new File(".");
			rootDir = canonical(rd);
		}
		File f = new File(fname);
		String cn = canonical(f);
		//print("  ::canonical: " + cn);
		cn = cn.substring(rootDir.length()+1);
		if (contains(cn)) return false;
		//print("  ::parent now: "+ getDir());
		includestack.add(cn);
		return true;
	}
	
	private boolean contains(String name) {
		for (String n : includestack) {
			if (n.equals(name)) return true;
		}
		return false;
	}
	
	public String pop() {
		if (includestack.size() > 0) { 
			//print("::pop(): " + includestack.get(includestack.size()-1));
			return includestack.remove(includestack.size()-1);
		}
		return null;
	}
	
	private String peek() {
		if (includestack.size() > 0) 
			return includestack.get(includestack.size()-1);
		return ".";
	}

	private String getDir() {
		File dir = new File(peek());
		return dir.getParent();
	}

	public String getFilenameWithPath(String fname) {
		String dir = getDir();
		if (!empty(dir)) return new File(dir) + File.separator + fname;
		return fname;
	}
	
	private String rootDir;
	
	private String canonical(File f) {
		try {
			return f.getCanonicalPath();
		} catch(Exception e) { 
			fail(e);
		}
		return null;
	}
	
}
